package com.example.lenovo_.myutils;

import android.os.Handler;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class SendRequest {

	public String TAG = "info";
	private SendUtils sendinfor;/* 请求的信息 */
	private Handler handler;

	public SendRequest(SendUtils sendinfor, Handler handler)// 请求的数据以及handler
	{
		this.sendinfor = sendinfor;
		this.handler = handler;
	}

	public void StartRequest() {
		// 新建线程
		new Thread() {
			public void run() {

				try {
					SendRequest();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	private void SendRequest() throws JSONException {
		// 通过HttpClient类与WEB服务器交互
		HttpClient httpClient = new DefaultHttpClient();
		// 定义与服务器交互的地址
		String ServerUrl = this.sendinfor.getRequestPath();
		// 一：连接超时：connectionTimeout指的是连接一个url的连接等待时间。
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		// 设置读取超时：指的是连接上一个url，获取response的返回等待时间
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
		// POST方式
		HttpPost httpRequst = new HttpPost(ServerUrl);

		// CookieStore mCookieStore = ((AbstractHttpClient)
		// httpClient).getCookieStore();
		// List<Cookie> cookies = mCookieStore.getCookies();

		try {
			// 准备传输的数据

			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();

			params.add(new BasicNameValuePair("json", this.sendinfor.getSendRequest().toString()));
			// 发送请求
			httpRequst.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			// 得到响应
			HttpResponse response = httpClient.execute(httpRequst);
			// 返回值如果为200的话则证明成功的得到了数据
			if (response.getStatusLine().getStatusCode() == 200) {
				Log.e(TAG, "连接成功 ");
				// Toast.makeText(this, "yes", 12);
				String result = "";
				// result = EntityUtils.toString(response.getEntity(), "UTF-8");
				// Log.e(TAG, result);

				StringBuilder builder = new StringBuilder();
				// 将得到的数据进行解析
				BufferedReader buffer = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				// readLine()阻塞读取
				for (String s = buffer.readLine(); s != null; s = buffer.readLine()) {
					builder.append(s);
				}

				Log.i(TAG, "读取到数据 ");
				System.out.println(builder.toString());
				// 获取读到的数据
				JSONObject json = new JSONObject(builder.toString());
				JSONObject jsonObject = json.getJSONObject("data");
				int flag = jsonObject.getInt("flag");
				this.sendinfor.setReceResponce(jsonObject);/* 返回的结果放到sendinfor */
				if (flag == 1)
					handler.sendEmptyMessage(1);// 成功
				else {
					handler.sendEmptyMessage(2);//
				}

			} else {
				handler.sendEmptyMessage(3);
			}

		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "请求错误 ");// 没有网会抛出异常（连不上）或者一个错的url（为何会超时不管用？秒显示）
			Log.e(TAG, e.getMessage());
			handler.sendEmptyMessage(4);
		}

		return;
	}
}
